package com.ang.normal;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author ssang
 * @date 2022-04-09 9:51
 * 工具类，获取连接以及关闭方法
 */
public class RabbitMqUtils {
    private static Connection connection;

    public static Connection getRabbitMqConnection() throws IOException, TimeoutException {
        if(connection == null || !connection.isOpen()){
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("192.168.1.90");
            factory.setPort(5672);
            factory.setUsername("admin");
            factory.setPassword("admin");
            factory.setVirtualHost("my_vhost");

            if(connection==null){
                connection = factory.newConnection();
            }
        }
        return connection;
    }


    public static void close(Connection conn, Channel channel){
        try{
            if(channel!=null){
                channel.close();
            }
            if(conn!=null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
